package week03.question03.gateway02;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpVersion;
import week03.question03.gateway02.filter.ProcessCalculateFilter;
import week03.question03.gateway02.filter.HttpRequestFilter;
import week03.question03.gateway02.filter.HttpResponseFilter;
import week03.question03.gateway02.httpclient.HttpClientDemo;

import java.io.UnsupportedEncodingException;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;

public class HttpHandler extends ChannelInboundHandlerAdapter {

    private String targetHttpServerUri;

    private ProcessCalculateFilter filter = new ProcessCalculateFilter();

    public HttpHandler(String targetHttpServerUri) {
        this.targetHttpServerUri = targetHttpServerUri;
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
        handle(fullHttpRequest, ctx, filter);
    }


    private void handle(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx, HttpRequestFilter requestFilter) throws UnsupportedEncodingException {
        requestFilter.filter(fullHttpRequest,ctx);
        String uri = fullHttpRequest.uri();
        String response = HttpClientDemo.doGet(targetHttpServerUri + uri.substring(1));
        DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, Unpooled.wrappedBuffer(response.getBytes("UTF-8")));
        defaultFullHttpResponse.headers().set("Content-Type","application/json");
        defaultFullHttpResponse.headers().setInt("Content-Length", defaultFullHttpResponse.content().readableBytes());
        afterHandler(defaultFullHttpResponse, ctx, filter);
    }

    private void afterHandler(FullHttpResponse fullHttpResponse, ChannelHandlerContext ctx,HttpResponseFilter responseFilter){
        responseFilter.filter(fullHttpResponse);
        ctx.write(fullHttpResponse).addListener(ChannelFutureListener.CLOSE);
    }
}
